﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using IEx.Common;
using IEx.Model;
using IEx.Utilities;

namespace IEx.ParserBuilder.FinanceReport
{
    public class HKExNewsRequestBuilder : DefaultRequestBuilder
    {
        public HKExNewsRequestBuilder() : base() { }

        public override void BeginBuildRequest(SourceItem item)
        {
            // Daily Url doesn't need to buid request
            if (!string.IsNullOrEmpty(item.DailyUrl) && item.DailyUrl.Equals(item.Url, StringComparison.OrdinalIgnoreCase))
                return;

            Repository announcementMgr = new Repository();
            DateTime latestDate = DateTime.Now ;
            if (string.IsNullOrEmpty(item.PrevResponseHtml))
            {
                latestDate = announcementMgr.GetLastestDateAnnouncement(item.SourceCode, item.SourceId, item.LangId);
            }

            this.InternalBuildRequest(item, latestDate, DateTime.Now);
        }

        protected void InternalBuildRequest(SourceItem item, DateTime from, DateTime to)
        {
            //STEP 1: get view state of search form
            string _ViewState = !string.IsNullOrEmpty(item.PrevResponseHtml) ?
                RegexUtility.ExtractViewState(item.PrevResponseHtml) : GetFormInfoFromSearchPage(item.Url);

            // assign values for search form
            this.Method = "POST";
            this.ContentType = "application/x-www-form-urlencoded";
            this.AttachRequestParam("__VIEWSTATE", _ViewState);
            this.AttachRequestParam("__VIEWSTATEENCRYPTED", "");
            if (string.IsNullOrEmpty(item.PrevResponseHtml))
            {
                this.AttachRequestParam("ctl00$txt_today", to.ToString("yyyyMMdd"));
                this.AttachRequestParam("ctl00$hfStatus", "AEM");
                this.AttachRequestParam("ctl00$hfAlert", "");
                this.AttachRequestParam("ctl00$txt_stock_code", item.SearchCode);
                this.AttachRequestParam("ctl00$txt_stock_name", "");
                this.AttachRequestParam("ctl00$rdo_SelectDocType", "rbAll");
                this.AttachRequestParam("ctl00$sel_tier_1", "-2");
                this.AttachRequestParam("ctl00$sel_DocTypePrior2006", "-1");
                this.AttachRequestParam("ctl00$sel_tier_2_group", "-2");
                this.AttachRequestParam("ctl00$sel_tier_2", "-2");
                this.AttachRequestParam("ctl00$ddlTierTwo", "23,1,3");
                this.AttachRequestParam("ctl00$ddlTierTwoGroup", "10,2");
                this.AttachRequestParam("ctl00$txtKeyWord", "");
                this.AttachRequestParam("ctl00$rdo_SelectDateOfRelease", "rbManualRange");
                this.AttachRequestParam("ctl00$sel_DateOfReleaseFrom_d", from.Date.Day.ToString("00"));
                this.AttachRequestParam("ctl00$sel_DateOfReleaseFrom_m", from.Date.Month.ToString("00"));
                this.AttachRequestParam("ctl00$sel_DateOfReleaseFrom_y", from.Date.Year.ToString());

                this.AttachRequestParam("ctl00$sel_DateOfReleaseTo_d", to.Day.ToString("00"));
                this.AttachRequestParam("ctl00$sel_DateOfReleaseTo_m", to.Month.ToString("00"));
                this.AttachRequestParam("ctl00$sel_DateOfReleaseTo_y", to.Year.ToString());
                this.AttachRequestParam("ctl00$sel_defaultDateRange", "SevenDays");
                this.AttachRequestParam("ctl00$rdo_SelectSortBy", "rbDateTime");
            }
            else
            {
                this.AttachRequestParam("ctl00$gvMain$ctl01$btnNext.x", "0");
                this.AttachRequestParam("ctl00$gvMain$ctl01$btnNext.y", "0");
            }
        }

        private static string GetFormInfoFromSearchPage(string requestURL)
        {
            // STEP 1: create GET request to get __VIEWSTATE of search form
            //Uri url = new Uri(requestURL);
            //// Get cookies value
            //HttpWebRequest requestGET = (HttpWebRequest)WebRequest.Create(url);
            //requestGET.Method = "GET";
            //StreamReader responseReader = new StreamReader(requestGET.GetResponse().GetResponseStream());
            
            HttpStatusCode code = HttpStatusCode.Found;
            string responseData = Utility.LoadHtml(requestURL, ref code);
            //responseReader.Close();



            // extract the viewstate value and build out POST data
            return RegexUtility.ExtractViewState(responseData);
        }
    }

    public class FinanceReportRequestBuilderUpdate : HKExNewsRequestBuilder
    {
        private string sourceCode;
        private int? languageId;
        private DateTime? dateFrom;
        private DateTime? dateTo;

        /// <summary>
        /// Create a new instance by providing the particular parameters
        /// </summary>
        /// <param name="sourceCode">Company code to find pressreleases</param>
        /// <param name="languageId">
        ///     Language Id to find relatively pressreleases. The value can accept NULL value.
        ///     When value is NULL, it means that for every languages
        /// </param>
        /// <param name="dateFrom">The date to start scanning from</param>
        /// <param name="dateTo">The date to start canning to</param>
        public FinanceReportRequestBuilderUpdate(string sourceCode, int? languageId, DateTime? dateFrom, DateTime? dateTo)
            : base()
        {
            this.sourceCode = sourceCode;
            this.languageId = languageId;
            this.dateFrom = dateFrom ?? new DateTime(1999, 1, 1);
            this.dateTo = dateTo ?? DateTime.Now;
        }

        public override void BeginBuildRequest(SourceItem item)
        {
            this.InternalBuildRequest(item, this.dateFrom.Value, this.dateTo.Value);
        }
    }
}
